package gang.org.springframework.boot.web.servlet.context;

import gang.org.springframework.boot.autoconfigure.web.servlet.server.GangServletWebServerFactory;
import gang.org.springframework.boot.web.embedded.tomcat.GangTomcatServletWebServerFactory;
import gang.org.springframework.boot.web.server.GangWebServer;
import gang.org.springframework.boot.web.servlet.GangServletContextInitializer;
import gang.org.springframework.boot.web.servlet.GangServletContextInitializerBeans;
import gang.org.springframework.framework.context.GangGenericWebApplicationContext;

import javax.servlet.ServletContext;
import java.util.Collection;

/**
 * @Author：gang.chen
 * @Date：2023/8/4 16:25
 */
public class GangServletWebServerApplicationContext extends GangGenericWebApplicationContext {

    private volatile GangWebServer webServer;


    @Override
    protected void onRefresh() {

        System.out.println("spring mvc 初始化...");

        // supper.onRefresh() TODD
        super.onRefresh();


        createWebServer();
    }

    private void createWebServer(){

        GangWebServer webServer = this.webServer;

        ServletContext servletContext = getServletContext();

        if (webServer == null && servletContext == null) {

            GangServletWebServerFactory factory = getWebServerFactory();

            this.webServer = factory.getWebServer(getSelfInitializer());


        }
        else if (servletContext != null)
        {
            //TODO
        }

        //TODO
        //initPropertySource

    }

    private GangServletWebServerFactory getWebServerFactory() {

        String[] beanNames = getBeanFactory().getBeanNamesForType(GangServletWebServerFactory.class);

        if (beanNames.length == 0) {
            //TODO
        }
        if (beanNames.length > 1) {
            //TODO
        }

        GangServletWebServerFactory bean = getBeanFactory().getBean(beanNames[0], GangServletWebServerFactory.class);

        return bean;
    }


    public GangServletContextInitializer getSelfInitializer()
    {
        //TODO
        return this::selfInitialize;
    }

    public void selfInitialize(ServletContext servletContext)
    {
        //prepareWebApplicationContext(servletContext) TODO

        //registerApplicationScope(servletContext) TODO

        //WebApplicationContextUtils.registerEnvironmentBeans() TODO

        Collection<GangServletContextInitializer> servletContextInitializerBeans = getServletContextInitializerBeans();

        for (GangServletContextInitializer beans : servletContextInitializerBeans){
            beans.onStartup(servletContext);
        }

    }

    private Collection<GangServletContextInitializer> getServletContextInitializerBeans() {
        return new GangServletContextInitializerBeans(getBeanFactory());
    }

}
